package com.zenithmind.version.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.version.pojo.dto.MergeRequestCreateDTO;
import com.zenithmind.version.pojo.dto.MergeRequestUpdateDTO;
import com.zenithmind.version.pojo.query.MergeRequestQueryDTO;
import com.zenithmind.version.pojo.vo.MergeRequestVO;
import com.zenithmind.version.service.MergeRequestService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 合并请求管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Tag(name = "合并请求管理", description = "合并请求管理相关接口")
@RestController
@RequestMapping("/api/v1/merge-requests")
@RequiredArgsConstructor
public class MergeRequestController {

    private final MergeRequestService mergeRequestService;

    @Operation(summary = "创建合并请求", description = "创建新的合并请求")
    @PostMapping
    public Result<MergeRequestVO> createMergeRequest(@Valid @RequestBody MergeRequestCreateDTO createDTO) {
        MergeRequestVO mergeRequest = mergeRequestService.createMergeRequest(createDTO);
        return Result.success(mergeRequest);
    }

    @Operation(summary = "更新合并请求", description = "更新合并请求信息")
    @PutMapping("/{id}")
    public Result<Boolean> updateMergeRequest(
            @Parameter(description = "合并请求ID") @PathVariable String id,
            @Valid @RequestBody MergeRequestUpdateDTO updateDTO) {
        Boolean result = mergeRequestService.updateMergeRequest(id, updateDTO);
        return Result.success(result);
    }

    @Operation(summary = "删除合并请求", description = "删除指定合并请求")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteMergeRequest(@Parameter(description = "合并请求ID") @PathVariable String id) {
        Boolean result = mergeRequestService.deleteMergeRequest(id);
        return Result.success(result);
    }

    @Operation(summary = "分页查询合并请求", description = "分页查询合并请求列表")
    @PostMapping("/page")
    public Result<IPage<MergeRequestVO>> getMergeRequestPage(@Valid @RequestBody MergeRequestQueryDTO queryDTO) {
        IPage<MergeRequestVO> page = mergeRequestService.getMergeRequestPage(queryDTO);
        return Result.success(page);
    }

    @Operation(summary = "获取合并请求详情", description = "获取合并请求详细信息")
    @GetMapping("/{id}")
    public Result<MergeRequestVO> getMergeRequestDetail(@Parameter(description = "合并请求ID") @PathVariable String id) {
        MergeRequestVO mergeRequest = mergeRequestService.getMergeRequestDetail(id);
        return Result.success(mergeRequest);
    }

    @Operation(summary = "获取仓库合并请求", description = "获取仓库的合并请求列表")
    @GetMapping("/repository/{repositoryId}")
    public Result<List<MergeRequestVO>> getRepositoryMergeRequests(
            @Parameter(description = "仓库ID") @PathVariable String repositoryId,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<MergeRequestVO> mergeRequests = mergeRequestService.getRepositoryMergeRequests(repositoryId, status, limit);
        return Result.success(mergeRequests);
    }

    @Operation(summary = "获取我创建的合并请求", description = "获取用户创建的合并请求")
    @GetMapping("/my")
    public Result<List<MergeRequestVO>> getUserMergeRequests(
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<MergeRequestVO> mergeRequests = mergeRequestService.getUserMergeRequests(userId, status, limit);
        return Result.success(mergeRequests);
    }

    @Operation(summary = "获取指派给我的合并请求", description = "获取指派给用户的合并请求")
    @GetMapping("/assigned")
    public Result<List<MergeRequestVO>> getAssignedMergeRequests(
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<MergeRequestVO> mergeRequests = mergeRequestService.getAssignedMergeRequests(userId, status, limit);
        return Result.success(mergeRequests);
    }

    @Operation(summary = "检查合并冲突", description = "检查分支合并冲突")
    @GetMapping("/check-conflicts")
    public Result<Object> checkMergeConflicts(
            @Parameter(description = "仓库ID") @RequestParam String repositoryId,
            @Parameter(description = "源分支") @RequestParam String sourceBranch,
            @Parameter(description = "目标分支") @RequestParam String targetBranch) {
        Object conflicts = mergeRequestService.checkMergeConflicts(repositoryId, sourceBranch, targetBranch);
        return Result.success(conflicts);
    }

    @Operation(summary = "获取合并请求变更", description = "获取合并请求的文件变更")
    @GetMapping("/{id}/changes")
    public Result<List<Object>> getMergeRequestChanges(@Parameter(description = "合并请求ID") @PathVariable String id) {
        List<Object> changes = mergeRequestService.getMergeRequestChanges(id);
        return Result.success(changes);
    }

    @Operation(summary = "获取合并请求提交", description = "获取合并请求的提交列表")
    @GetMapping("/{id}/commits")
    public Result<List<Object>> getMergeRequestCommits(@Parameter(description = "合并请求ID") @PathVariable String id) {
        List<Object> commits = mergeRequestService.getMergeRequestCommits(id);
        return Result.success(commits);
    }

    @Operation(summary = "执行合并", description = "执行合并请求")
    @PostMapping("/{id}/merge")
    public Result<Object> executeMerge(@Parameter(description = "合并请求ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Object result = mergeRequestService.executeMerge(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "关闭合并请求", description = "关闭合并请求")
    @PostMapping("/{id}/close")
    public Result<Boolean> closeMergeRequest(
            @Parameter(description = "合并请求ID") @PathVariable String id,
            @Parameter(description = "关闭原因") @RequestParam(required = false) String reason) {
        String userId = UserContext.getUserId();
        Boolean result = mergeRequestService.closeMergeRequest(id, userId, reason);
        return Result.success(result);
    }

    @Operation(summary = "重新打开合并请求", description = "重新打开合并请求")
    @PostMapping("/{id}/reopen")
    public Result<Boolean> reopenMergeRequest(@Parameter(description = "合并请求ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = mergeRequestService.reopenMergeRequest(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "添加审核者", description = "添加合并请求审核者")
    @PostMapping("/{id}/reviewers")
    public Result<Boolean> addReviewer(
            @Parameter(description = "合并请求ID") @PathVariable String id,
            @Parameter(description = "审核者ID") @RequestParam String reviewerId) {
        String userId = UserContext.getUserId();
        Boolean result = mergeRequestService.addReviewer(id, reviewerId, userId);
        return Result.success(result);
    }

    @Operation(summary = "移除审核者", description = "移除合并请求审核者")
    @DeleteMapping("/{id}/reviewers/{reviewerId}")
    public Result<Boolean> removeReviewer(
            @Parameter(description = "合并请求ID") @PathVariable String id,
            @Parameter(description = "审核者ID") @PathVariable String reviewerId) {
        Boolean result = mergeRequestService.removeReviewer(id, reviewerId);
        return Result.success(result);
    }

    @Operation(summary = "提交审核意见", description = "提交合并请求审核意见")
    @PostMapping("/{id}/review")
    public Result<Boolean> submitReview(
            @Parameter(description = "合并请求ID") @PathVariable String id,
            @Parameter(description = "审核状态") @RequestParam Integer status,
            @Parameter(description = "审核意见") @RequestParam(required = false) String comment) {
        String userId = UserContext.getUserId();
        Boolean result = mergeRequestService.submitReview(id, userId, status, comment);
        return Result.success(result);
    }

    @Operation(summary = "获取审核记录", description = "获取合并请求的审核记录")
    @GetMapping("/{id}/reviews")
    public Result<List<Object>> getMergeRequestReviews(@Parameter(description = "合并请求ID") @PathVariable String id) {
        List<Object> reviews = mergeRequestService.getMergeRequestReviews(id);
        return Result.success(reviews);
    }

    @Operation(summary = "搜索合并请求", description = "根据关键词搜索合并请求")
    @GetMapping("/search")
    public Result<List<MergeRequestVO>> searchMergeRequests(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "仓库ID") @RequestParam(required = false) String repositoryId,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<MergeRequestVO> mergeRequests = mergeRequestService.searchMergeRequests(keyword, repositoryId, status, limit);
        return Result.success(mergeRequests);
    }

    @Operation(summary = "获取合并请求统计", description = "获取合并请求统计信息")
    @GetMapping("/repository/{repositoryId}/statistics")
    public Result<Object> getMergeRequestStatistics(@Parameter(description = "仓库ID") @PathVariable String repositoryId) {
        Object statistics = mergeRequestService.getMergeRequestStatistics(repositoryId);
        return Result.success(statistics);
    }

    @Operation(summary = "获取用户统计", description = "获取用户合并请求统计")
    @GetMapping("/my/statistics")
    public Result<Object> getUserMergeRequestStatistics() {
        String userId = UserContext.getUserId();
        Object statistics = mergeRequestService.getUserMergeRequestStatistics(userId);
        return Result.success(statistics);
    }

    @Operation(summary = "检查自动合并", description = "检查是否可以自动合并")
    @GetMapping("/{id}/can-auto-merge")
    public Result<Boolean> canAutoMerge(@Parameter(description = "合并请求ID") @PathVariable String id) {
        Boolean canMerge = mergeRequestService.canAutoMerge(id);
        return Result.success(canMerge);
    }

    @Operation(summary = "获取合并预览", description = "获取合并预览")
    @GetMapping("/merge-preview")
    public Result<Object> getMergePreview(
            @Parameter(description = "仓库ID") @RequestParam String repositoryId,
            @Parameter(description = "源分支") @RequestParam String sourceBranch,
            @Parameter(description = "目标分支") @RequestParam String targetBranch) {
        Object preview = mergeRequestService.getMergePreview(repositoryId, sourceBranch, targetBranch);
        return Result.success(preview);
    }

    @Operation(summary = "解决合并冲突", description = "解决合并冲突")
    @PostMapping("/{id}/resolve-conflicts")
    public Result<Object> resolveMergeConflicts(
            @Parameter(description = "合并请求ID") @PathVariable String id,
            @RequestBody Object conflictResolutions) {
        String userId = UserContext.getUserId();
        Object result = mergeRequestService.resolveMergeConflicts(id, conflictResolutions, userId);
        return Result.success(result);
    }
}
